﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace ImgURLUploader
{
    class Program
    {
        
        // 配置文件实体
        public static ConfigModel config = new ConfigModel();

        // 命令语法要求：ImgURLUploader up "c:\\12.png" "c:\\123.png"
        static void Main(string[] args)
        {
            try
            {
                #region 解析输入命令行的参数

                string ver =  System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
               
                if ((args.Length == 0)||args[0].ToLower().Equals("--help"))
                {
                    Console.WriteLine("");
                    Console.WriteLine("感谢使用ImgURLUploader上传程序，当前版本："+ ver);
                    Console.WriteLine("");
                    Console.WriteLine("命令语法要求：ImgURLUploader up \"c:\\\\12.png\" \"c:\\\\123.png\"");
                    Console.WriteLine("");
                    Console.WriteLine("使用 ImgURLUploader --des \"密码\" ,进行加密");
                    Console.WriteLine("");
                    return;
                }
                if (args[0].ToLower().Equals("--des"))
                {
                    String pwd= DES.DesEncrypt(args[1], DES.DESKey);
                    Console.WriteLine(pwd);
                    return;

                }
                if (args.Length < 2)
                {
                    Console.WriteLine("输入参数不正确,请检查一下。");
                    return;
                }
                if (!args[0].ToLower().Equals("up"))
                {
                    Console.WriteLine("输入的参数不正确,请检查一下。");
                    return;
                }



                #region 初始化配置文件

                if (!Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\Logs"))
                {
                    System.IO.Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + "\\Logs");
                }
                if (!Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\ImgURLUploaderTmp"))
                {
                    System.IO.Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + "\\ImgURLUploaderTmp");
                }
                if (!File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\ImgURLUploder.conf"))
                {
                    SerializeClassHelper.SerializeObject(System.AppDomain.CurrentDomain.BaseDirectory + "\\ImgURLUploder.conf", config);
                }
                config = (ConfigModel)SerializeClassHelper.DeserializeObject(System.AppDomain.CurrentDomain.BaseDirectory + "\\ImgURLUploder.conf");
                config.Password = DES.DesDecrypt(config.Password,DES.DESKey);
                #endregion


                #region 删除文件
                DirectoryInfo di = new DirectoryInfo(System.AppDomain.CurrentDomain.BaseDirectory + "\\ImgURLUploaderTmp");
                FileInfo[] files = di.GetFiles();
                foreach (var item in files)
                {
                    File.Delete(item.FullName);
                }
                #endregion

                // 将图片的url地址保存下来
                List<string> ImgList = new List<string>();
                for (int i = 1; i < args.Length; i++)
                {
                    string str = args[i];
                    if (str.StartsWith("http"))
                    {
                        // 处理网络图片
                        ImgList.Add(Images.GetImageFile(System.AppDomain.CurrentDomain.BaseDirectory + "\\ImgURLUploaderTmp", str));
                    }
                    else
                    {
                        // 处理本地图片
                        ImgList.Add(args[i]);
                    }

                }
                #endregion

             

                #region 进行登陆
                string LoginURL = config.BaseImgURL + config.VerifyURL;
                string UserName = config.UserName;
                string Password = config.Password;

                string postData = "user=" + UserName + "&password=" + Password;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(LoginURL));
                webRequest.Method = "post";
                webRequest.Accept = "application/json, text/javascript, */*; q=0.01";
                webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36";
                
                webRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
                webRequest.ContentLength = byteArray.Length;
                System.IO.Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                WebHeaderCollection repHeader = response.Headers;
                string data = new System.IO.StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();

                if (!repHeader.AllKeys.Contains("Set-Cookie"))
                {
                    Console.WriteLine("登陆请求有误,请检查一下。");
                    return;
                }

                string token = "";
                foreach(string str in repHeader.GetValues("Set-Cookie"))
                {
                    if (str.ToLower().Contains("token"))
                    {
                        string[] cookieArry = str.Split(';');
                        foreach(string tokenstr in cookieArry)
                        {
                            if (tokenstr.ToLower().Contains("token"))
                            {
                                token = tokenstr.Split('=')[1];
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }

                
                Dictionary<string, string> dataDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
                if (token.Equals("")||(!dataDic["code"].Equals("200")))
                {
                    Console.WriteLine("登陆请求有误,请检查一下,返回数据为: "+data+",token为: "+token);
                    return;
                }

                #endregion

                #region 上传图片
                string UploadURL = config.BaseImgURL + config.UploadURL;
                List<string> RetURLList = new List<string>();
                foreach (string imgPath in ImgList)
                {
                    Console.WriteLine("Uploading: "+imgPath);

                    string postData2 = "user=" + UserName + "&password=" + Password;
                    byte[] byteArray2 = Encoding.UTF8.GetBytes(postData2);
                    HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(new Uri(UploadURL));
                    webRequest2.Method = "post";
                    webRequest2.Accept = "application/json, text/javascript, */*; q=0.01";
                    webRequest2.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36";

                    webRequest2.Headers.Add("Cookie", "user=" + config.UserName + "; token=" + token + "");

                    string boundary = DateTime.Now.Ticks.ToString("X");
                    webRequest2.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                    byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                    int pos = imgPath.LastIndexOf("\\");
                    string fileName = imgPath.Substring(pos + 1);

                    //请求头部信息
                    StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                    FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                    byte[] bArr = new byte[fs.Length];
                    fs.Read(bArr, 0, bArr.Length);
                    fs.Close();

                    Stream postStream = webRequest2.GetRequestStream();
                    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                    postStream.Write(bArr, 0, bArr.Length);
                    postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                    postStream.Close();


                    HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
                    string data2 = new System.IO.StreamReader(response2.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();


                    Dictionary<string, string> data2Dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(data2);

                    RetURLList.Add(data2Dic["url"].ToString());

                    if (data2Dic["id"].ToLower() != "false")
                    {
                        string dealurl = config.BaseImgURL + config.DealURL + data2Dic["id"];
                        HttpWebRequest webRequest3 = (HttpWebRequest)WebRequest.Create(new Uri(dealurl));
                        webRequest3.Method = "get";
                        webRequest3.Accept = "application/json, text/javascript, */*; q=0.01";
                        webRequest3.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36";

                        webRequest3.Headers.Add("Cookie", "user=" + config.UserName + "; token=" + token + "");
                        HttpWebResponse response3 = (HttpWebResponse)webRequest3.GetResponse();
                        string data3 = new System.IO.StreamReader(response3.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();

                        string strFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + string.Format("{0}.txt", DateTime.Now.ToString("yyyy-MM-dd"));
                        System.IO.FileStream fs1 = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
                        System.IO.StreamWriter sw = new System.IO.StreamWriter(fs1, System.Text.Encoding.Default);
                        sw.Write("处理成功，id"+ data2Dic["id"]+"\r\n");
                        sw.Close();
                        fs.Close();
                    }


                }

                #endregion


                
                #region 输出结果
                if (RetURLList.Count!= ImgList.Count)
                {
                    Console.WriteLine("Upload Failed");
                    return;
                }
                Console.WriteLine("Upload Success");
                foreach (string url in RetURLList)
                {
                    Console.WriteLine(url);
                }
                #endregion

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                string strFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\" + string.Format("{0}.txt", DateTime.Now.ToString("yyyy-MM-dd"));
                System.IO.FileStream fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
                System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
                sw.Write(string.Join(",", args).ToString() + "\r\n");
                sw.Write(ex.Message + "\r\n");
                sw.Close();
                fs.Close();
            }
            

          
        }


    }
}
